package rediscli

import (
	"biliMiddleware/global"
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/go-redis/redis/v8"
)

var (
	client *redis.Client
	ctx    = context.Background()
)

func init() {
	c := global.Config.Redis

	client = redis.NewClient(&redis.Options{
		Addr:         c.Address,
		Password:     c.Password, // no password set
		DB:           c.DB,       // use default DB
		PoolSize:     100,
		MinIdleConns: 10,
		DialTimeout:  5 * time.Second,
		ReadTimeout:  1 * time.Second,
		WriteTimeout: 1 * time.Second,
		PoolTimeout:  2 * time.Second,
	})

	pong, err := client.Ping(ctx).Result()
	if err != nil {
		fmt.Println("初始化失败")
	} else {
		fmt.Println("redis connect ping response:", pong)
	}
	ClearProxyList()
}

// GetClientAllKey 获取所有在线客户端key
func GetClientAllKey() (keys []string) {
	var cursor uint64
	for {
		var key []string
		var err error
		key, cursor, err = client.Scan(ctx, cursor, "*", 10).Result()
		for _, s := range key {
			if !strings.Contains(s, "list") {
				keys = append(keys, s)
			}
		}
		if err != nil {
			panic(err)
		}
		if cursor == 0 {
			break
		}
	}
	return keys
}

// SetTaskList 设置任务列表
func SetTaskList(key string, date interface{}) {
	key = fmt.Sprintf("list-%v", key)
	val := client.RPush(ctx, key, date).Val()
	if val == 0 {
		global.Log.Errorf("func:RedisSetList -> \n\tval := :%v\n", val)
	}
	client.Expire(ctx, key, time.Second*20)
}

// ClearProxyList 清除代理列表
func ClearProxyList() {
	client.Del(ctx, "proxy-list")
}

// SetProxyStr 设置代理列表
func SetProxyStr(str string) {
	client.RPush(ctx, "proxy-list", str)
}

// GetProxyStr 获取所有代理
func GetProxyStr() []string {
	if client.Exists(ctx, "proxy-list").Val() == 1 {
		result, err := client.LRange(ctx, "proxy-list", 0, -1).Result()
		if err != nil {
			panic(err)
		}
		return result
	}
	return nil
}

// SetTaskStatusStr 把更新状态结果卸载缓存中
func SetTaskStatusStr(body []byte) error {
	return client.Set(ctx, "task-status-list", body, 0).Err()
}

// SetClientHash 设置客户端的hash值
func SetClientHash(body string) error {
	key := "client_hash_list"
	return client.Set(ctx, key, body, 0).Err()
}
